#!/usr/bin/env python3
"""
反应器控制系统主入口
Laboratory Reactor Control System Main Entry Point
"""

import sys
import os
from pathlib import Path

# 添加src目录到Python路径
sys.path.insert(0, str(Path(__file__).parent / "src"))

# 现在可以导入我们的模块
from src.web.app import app, system_state, stop_event
from src.utils.simple_logging import get_app_logger

# 获取主应用日志记录器
logger = get_app_logger("startup")

if __name__ == "__main__":
    try:
        # 启动时删除锁文件
        from src.utils.config import LOCK_FILE
        
        if Path(LOCK_FILE).exists():
            try:
                Path(LOCK_FILE).unlink()
                logger.info(f"启动时已删除锁文件：{LOCK_FILE}")
            except Exception as e:
                logger.error(f"启动时删除锁文件失败: {e}")
        
        # 重置设备状态
        system_state.device_status = 'idle'
        system_state.reaction_paused = False
        system_state.save_state()
        
        logger.info("Flask应用准备启动...")
        
        # 启动Flask应用
        app.run(host="0.0.0.0", port=5000, debug=False)
        
    except KeyboardInterrupt:
        logger.info("接收到中断信号，正在关闭应用...")
    except Exception as e:
        logger.error(f"应用启动失败: {e}")
    finally:
        # 确保程序退出时停止所有任务
        stop_event.set()
        system_state.save_state()
        logger.info("应用已安全关闭")
